package com.qf.carlikeboot.controller;

import com.qf.carlikeboot.domain.User;
import com.qf.carlikeboot.service.UserService;
import com.qf.carlikeboot.utils.MailUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.Objects;


@Controller
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/sendEmail")
    public String sendEmail(String email, HttpSession session) {
        // 生成一个验证码，可以是一个随机
        String code = RandomStringUtils.randomNumeric(5);
        // 把验证码放入session中，下次登录请求进来时可以比对验证码
        session.setAttribute("code", code);
        // 发送邮件
        MailUtils.sendMail(email, "名片系统验证码", "您的验证码是:" + code);
        return "成功";
    }


    @PostMapping("/login")
    public String login(String username, String password, String code, HttpSession session, Model model) {
        String sessionCode = (String) session.getAttribute("code");
        // 比对用户输入的验证码是否正确
        if (Objects.equals(sessionCode, code)) {
            // 如果正确，在调用业务等登录方法
            User login = userService.login(username, password);
            if (Objects.nonNull(login)) {
                return "welcome";
            } else {
                model.addAttribute("msg", "用户名或密码错误");
                // 登录错误的提示
                return "index";
            }
        } else {
            model.addAttribute("msg", "邮箱验证码错误");
            // 登录错误的提示
            return "index";
        }
    }

}
